import React, {useEffect, useState} from 'react';
import {Table, Button, message, Modal, Form, Input, Tag, Row, Col, Checkbox, Layout} from 'antd';
import {connect} from 'react-redux';
import {post, get} from '../../utils';
import {mUrl, config} from "../../config";
import Tooltip from "antd/es/tooltip";
import {
    PlusOutlined,
    ReloadOutlined,
    StopOutlined,
    CheckCircleOutlined,
    DeleteOutlined,
    EditOutlined
} from "@ant-design/icons";
import utils from "../../utils/utils";
import {defaultPagination} from "./publicComponents";
    
const {formItemLayout} = config;
const Role = () => {
    const [form] = Form.useForm();
    const [roleVisible, setRoleVisible] = useState(false);
    const [loading, setLoading] = useState(false); // 加载
    const [dataList, setDataList] = useState([]); // 表格列表
    const [roleData, setRoleData] = useState({}); // 权限列表
    const [addOrEdit, setAddOrEdit] = useState(false);
    const [pagination, setPagination] = useState(Object.assign({}, defaultPagination)); // 表格分页
    const permissionids = utils.getData('permissionids'); // 获取本地缓存权限ID
    
    const columns = [
        {
            title: '序号',
            align: 'center',
            width: 80,
            key: 'roleid',
            dataIndex: 'roleid',
            render: (text, record, index) => ((pagination.pageSize * (pagination.current ? pagination.current - 1 : 0)) + index + 1)
        },
        {
            title: '操作',
            align: 'center',
            width: 250,
            render: data => {
                let text;
                let rolestate;
                let color;
                if (data.rolestate === 1) {    //是否启用(-1,停用 1,启用)
                    text = '停用';
                    rolestate = -1;
                    color = 'red';
                } else {
                    text = '启用';
                    rolestate = 1;
                    color = 'rgba(22, 155, 213, 1)';
                }
                return (<div>
                    <Button style={{color: color}}
                            size='small'
                            className='btnRight'
                            onClick={() => handleDelete(data, rolestate, text)}>
                        {
                            data.rolestate === -1 ?  <CheckCircleOutlined/> : <StopOutlined/> 
                        }
                        {text}
                    </Button>
                    <Button
                        size='small'
                        type={'danger'}
                        className='btnRight'
                        onClick={() => handleDelete(data, -2, '删除')}><DeleteOutlined/>删除</Button>
                    <Button
                        size='small'
                        type={'primary'}
                        className='btnRight'
                        onClick={() => handleUpdate(data)}><EditOutlined/>编辑</Button>
                </div>);
            }
        },
        {
            title: '角色名称',
            align: 'center',
            dataIndex: 'rolename',
        },
        {
            title: '角色描述',
            align: 'center',
            dataIndex: 'remark',
            render: remark => {
                let text = remark || '--';
                return (
                    <Tooltip placement={'topLeft'} title={remark}>
                        {text.length > 15 ? text.substr(0, 15) + '...' : text}
                    </Tooltip>
                );
            }
        },
        {
            title: '状态',
            align: 'center',
            dataIndex: 'rolestate',
            render: rolestate => {
                let text;
                if (rolestate === 1) {
                    text = '可用';
                } else {
                    text = '停用';
                }
                return (
                    <Tooltip placement={'topLeft'} >
                        <Tag color={rolestate !== 1 ? '#ff4d4f' : '#0da8de'}>{text}</Tag>
                    </Tooltip>
                );
            },
        }
    ];
    
    // 查询所有角色
    const findAll = async (params={}) => {
        let start = 1;
        if (params.startList > 1) {
            start = params.startList;
        }
        setLoading(true);
        const res = await get(mUrl.searchAllRole, {
            pageNo: start,
            pageSize: pagination.pageSize,
            ...params
        });
        setLoading(false);
        if (res.state === 1) {
            pagination.total = res.data.count;
            setPagination(pagination);
            setDataList(res.data);
        }
    };

    useEffect(() => {
        findAll();
    }, []);

    //修改角色
    const handleUpdate = async (data) => {
        if (permissionids) {
            if (permissionids.indexOf('2021010202') !==-1) {
                setAddOrEdit(true);
                const res = await get(mUrl.searchRoleDetail, {roleid: data.roleid});
                if (res.state === 1) {
                    setRoleData(res.data);
                    setRoleVisible(true);
                } 
            } else {
                message.warning('对不起您暂时没有修改角色的权限');
            }
        }
    };

    //删除角色
    const handleDelete = async (data, rolestate, text) => {
        if (permissionids) {
            if (permissionids.indexOf('2021010203') !==-1) {
                const res = await get(mUrl.searchRoleDetail, {roleid: data.roleid});
                if (res.state === 1) {
                    Modal.confirm({
                        title: '提示',
                        content: <span>是否确定将角色<span style={{color: 'red'}}>{data.name}</span>{text}？</span>,
                        onOk: async () => {
                            const {state} = await post(mUrl.updateRole, {...res.data, rolestate});
                            if (state === 1) {
                                message.success(text+"成功");
                                findAll();
                            }
                        }
                    });
                }
            } else {
                message.warning('对不起您暂时没有删除角色的权限！');
            }
        }
    };
    
    // 新建角色
    const add = ()=>{
        if (permissionids) {
            if(permissionids.indexOf('2021010201') !== -1) {
                setRoleVisible(true);
                setAddOrEdit(false);
                setRoleData({});
            } else {
                message.warning('对不起您暂时没有新建角色的权限！');
            }
        }
    };
    
    const handleTableChange = (page) => {
        pagination.current = page.current;
        pagination.pageSize = page.pageSize;
        setPagination(pagination);
        findAll({
            startList: pagination.current
        });
    };
    
    return (
        <div style={{padding: 14, background: '#fff', minHeight: 360}}>
            <label><p>权限管理 / 权限管理</p></label>
            <div style={{marginBottom: 10}}>
                <Button
                    type={'primary'}
                    className='btnRight'
                    onClick={add}>
                    <PlusOutlined/>新建
                </Button>
                <Button
                    type={'primary'}
                    onClick={() => findAll()}>
                    <ReloadOutlined/>刷新
                </Button>
            </div>
            <Table size="small"
                   rowKey={record => record.roleid}
                   dataSource={dataList}
                   columns={columns}
                   pagination={pagination}
                   loading={loading}
                   bordered
                   onChange={handleTableChange} 
            />
            <RoleModal
                form={form}
                getContainer={false}
                addOrEdit={addOrEdit}
                roleData={roleData}
                visible={roleVisible}
                onCancel={() => setRoleVisible(false)}
                onSubmit={() => {
                    findAll();
                    setRoleVisible(false);
                }}
            />
        </div>
    );
};

const RoleModal = ({form, visible, roleData, onSubmit, onCancel, addOrEdit = false}) => {
    const [loading, setLoading] = useState(false);
    const [allAuth, setAllAuth] = useState([]);
    const [selectAuth, setSelectAuth] = useState([]);
    const [authList, setAuthList] = useState([]);
    
    useEffect(() => {
        if (!visible) {
            form.resetFields();
            setSelectAuth([]);
        } else {
            if (roleData.roleid) {
                form.setFieldsValue({
                    rolename: roleData.rolename,
                    remark: roleData.remark,
                });
                let permissionids = [];
                if (roleData.permissionids) {
                    permissionids = roleData.permissionids.split(',');
                }
                setSelectAuth(permissionids);
            }
        }
    }, [visible]);

    useEffect(() => {
        searchAllAuth();
    }, []);
    
    // 查询所有权限
    const searchAllAuth = async () => {
        const res = await get(mUrl.searchAllAuthInfo, {});
        if (res.state === 1) {
            setAllAuth(res.data[0].moduleList);
        }
    };

    const onFinish = async (values) => {
        setLoading(true);
        let permissionids = [];
        const pushList = (data) => {
            data.forEach((item) => {
                if (item.ischeck) {
                    permissionids.push(item.id);
                    if (item.authList) {
                        pushList(item.authList);
                    } else if (item.functionList) {
                        pushList(item.functionList);
                    }
                }
            });
        };
        pushList(authList);
        let url = mUrl.addRole;
        if (roleData.roleid) {
            url = mUrl.updateRole;
            values.roleid = roleData.roleid;
            
        }
        values.permissionids = permissionids.join();
        const res = await post(url, values);
        if (res.state === 1) {
            onSubmit();
            setTimeout(()=>{
                setLoading(false);
            },800);
        }else {
            setTimeout(()=>{
                setLoading(false);
            },800);
            
        }
    };

    return (
        <Modal
            visible={visible}
            title={addOrEdit ? '修改角色' : '添加角色'}
            footer={false}
            onCancel={onCancel}
            width='80%'
            getContainer={false}
        >
            <div>
                <Form
                    form={form}
                    onFinish={onFinish}
                >
                    <Form.Item name={"rolename"}
                               label={'角色'}
                               {...formItemLayout}
                               rules={[{required: true, message: '请输入角色'}]}
                               style={{marginBottom: 15}}>
                        <Input placeholder={'请输入角色'}/>
                    </Form.Item>
                    <Form.Item name={"remark"}
                               {...formItemLayout}
                               label={'角色描述'}
                               style={{marginBottom: 15}}>
                        <Input.TextArea rows={2} placeholder={'请输入角色描述'}/>
                    </Form.Item>
                    <Form.Item label='菜单权限' {...formItemLayout}>
                        <SelectMenu
                            change={(authList) => setAuthList(authList)}
                            allAuth={allAuth} 
                            selectAuth={selectAuth}/>
                    </Form.Item>
                    <Form.Item style={{marginTop: 10, textAlign: 'center'}}>
                        <Button
                            loading={loading} htmlType="submit" type={'primary'}
                        >提交</Button>
                        <Button style={{marginLeft: 15}}
                                loading={loading} 
                                onClick={onCancel}
                        >取消</Button>
                    </Form.Item>
                </Form>
            </div>
        </Modal>
    );
};

//增加职位
const SelectMenu = ({allAuth = [], selectAuth = [], change}) => {
    const [upload, setUpload] = useState(false);
    const [authList, setAuthList] = useState([]);

    useEffect(() => {
        const list = JSON.parse(JSON.stringify(allAuth));
        const selectCheck = (data) => {
            data.forEach((item) => {
                const index = selectAuth.findIndex((key) => item.id === key);
                if (index !== -1) {
                    item.ischeck = true;
                } 
                if (item.authList) {
                    selectCheck(item.authList);
                } else if (item.functionList) {
                    selectCheck(item.functionList);
                }
            });
        };
        selectCheck(list);
        setAuthList(Object.assign([], list));
    }, [allAuth, selectAuth]);

    // 生成三级菜单
    const buildLevel3Menu = (data = [], props) => {
        const propsCheck = (data, parentid) => {
            const index = data.findIndex(({id}) => id === parentid);
            if (index !== -1) {
                data[index].ischeck = true;
            } else {
                data.forEach((item) => {
                    if (item.functionList) {
                        propsCheck(item.functionList, parentid);
                    }
                });
            }
        };
        return data.map((mItem, mIndex) => {
            return (
                <span key={mIndex.toString()} style={{marginRight: 20}}>
                    <Checkbox
                        onChange={() => {
                            mItem.ischeck = !mItem.ischeck;
                            if (mItem.ischeck) {
                                props.ischeck = true;
                                if (props.parentid) {
                                    propsCheck(allAuth, props.parentid);
                                }
                            }
                            change(authList);
                            setUpload(!upload);
                        }}
                        checked={mItem.ischeck}>
                        {mItem.name}
                    </Checkbox>
                </span>
            );
        });
    };

    // 生成一级菜单
    const buildLevelMenu = (data, className, props) => {
        return data.map((mItem, mIndex) => {
            return (
                <Row key={mIndex.toString()} className={className}
                     style={{height: 'auto', minHeight: mItem.functionList ? 35 : 'auto'}}>
                    <Col span={4}>
                        <Checkbox onChange={(e) => handleLevelMenuChange(mItem, e, props)}
                                  checked={mItem.ischeck}>{mItem.name}</Checkbox>
                    </Col>
                    {
                        mItem.functionList ?
                            <Col span={20}>
                                {buildLevelMenu(mItem.functionList, "level2Menu", mItem)}
                            </Col>
                            :
                            (
                                mItem.authList &&
                                <Col span={20} style={{
                                    backgroundColor: '#ffd1d1',
                                    paddingLeft: 5,
                                    marginBottom: mItem.parentid ? 5 : 10,
                                    justifyContent: 'center'
                                }}>
                                    {buildLevel3Menu(mItem.authList, mItem)}
                                </Col>
                            )
                    }
                </Row>
            );
        });
    };

    // 菜单改变
    const handleLevelMenuChange = (data, e, props) => {
        const isChecked = e.target.checked;
        data.ischeck = isChecked;
        if (props && isChecked) {
            props.ischeck = true;
        }
        const setChecked = (data) => {
            data.forEach(item => {
                // 判断子级菜单
                item.ischeck = isChecked;
                if (item.functionList) {
                    setChecked(item.functionList);
                } else if (item.authList) {
                    setChecked(item.authList);
                }
                
            });
        };
        if (data.functionList || data.authList) {
            setChecked(data.functionList || data.authList);
        }
        setUpload(!upload);
        change(authList);
        // this.setState({});
    };
    
    return (
        <Layout style={{height: '100%'}}>
            <Layout.Content style={{height: 500, overflow: 'scroll'}}>
                {buildLevelMenu(authList, "level1Menu")}
            </Layout.Content>
        </Layout>
    );
};

const mapStateToProps = (state) => {
    return {
        ...state.appReducer, // 全局的reducers
    };
};

export default connect(mapStateToProps)(Role);
